package org.example.rubbish.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.example.rubbish.common.PageResult;
import org.example.rubbish.dto.AdminUserDTO;
import org.example.rubbish.entity.AdminUser;
import org.example.rubbish.service.AdminUserService;
import org.example.rubbish.vo.AdminLoginRequest;
import org.example.rubbish.vo.AdminLoginResult;
import org.example.rubbish.vo.AdminLoginResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/admin/auth")
@Validated
public class AdminAuthController {

    private static final Logger logger = LoggerFactory.getLogger(AdminAuthController.class);

    private final AdminUserService adminUserService;

    @Autowired
    public AdminAuthController(AdminUserService adminUserService) {
        this.adminUserService = adminUserService;
    }

    @PostMapping("/login")
    public ResponseEntity<AdminLoginResponse> login(@Valid @RequestBody AdminLoginRequest loginRequest,
                                                    HttpServletRequest request) {
        try {
            AdminLoginResult result = adminUserService.login(
                    loginRequest.getUsername(),
                    loginRequest.getPassword(),
                    request
            );

            AdminUser adminUser = result.getAdminUser();
            AdminLoginResponse response = new AdminLoginResponse();
            response.setToken(result.getToken());
            response.setUsername(adminUser.getUsername());
            response.setRole(adminUser.getRole());
            response.setRealName(adminUser.getRealName());
            response.setDepartment(adminUser.getDepartment());
            response.setUserId(adminUser.getId());
            response.setLoginTime(result.getLoginTime());
            response.setLoginIp(result.getLoginIp());
            response.setStatus(adminUser.getStatus());
            response.setMessage("登录成功");

            logger.info("用户登录成功: {}", adminUser.getUsername());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("登录失败: {}", e.getMessage());
            AdminLoginResponse errorResponse = new AdminLoginResponse();
            errorResponse.setMessage("登录失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorResponse);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody AdminUserDTO adminUserDTO) {
        try {
            AdminUser adminUser = convertToEntity(adminUserDTO);
            AdminUser newAdmin = adminUserService.createAdminUser(adminUser);
            return ResponseEntity.ok(newAdmin);
        } catch (Exception e) {
            logger.error("注册失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body("注册失败: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public ResponseEntity<PageResult<AdminUser>> getAdminList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {

        try {
            PageResult<AdminUser> result = adminUserService.getAdminsWithPagination(page, size, keyword);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取管理员列表失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getAdminById(@PathVariable Long id) {
        try {
            AdminUser admin = adminUserService.getAdminById(id);
            return ResponseEntity.ok(admin);
        } catch (Exception e) {
            logger.error("获取管理员信息失败: {}", e.getMessage());
            return ResponseEntity.notFound().build();
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateAdmin(@PathVariable Long id,
                                         @Valid @RequestBody AdminUserDTO adminUserDTO) {
        try {
            AdminUser adminUser = convertToEntity(adminUserDTO);
            adminUser.setId(id);
            AdminUser updatedAdmin = adminUserService.updateAdminUser(adminUser);
            return ResponseEntity.ok(updatedAdmin);
        } catch (Exception e) {
            logger.error("更新管理员失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body("更新失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteAdmin(@PathVariable Long id) {
        try {
            adminUserService.softDeleteAdmin(id);
            return ResponseEntity.ok("管理员删除成功");
        } catch (Exception e) {
            logger.error("删除管理员失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body("删除失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<String> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            adminUserService.updateStatus(id, status);
            return ResponseEntity.ok("状态更新成功");
        } catch (Exception e) {
            logger.error("更新状态失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body("状态更新失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}/password")
    public ResponseEntity<String> changePassword(@PathVariable Long id,
                                                 @RequestBody ChangePasswordRequest request) {
        try {
            if (request.getNewPassword() == null || request.getNewPassword().trim().isEmpty()) {
                return ResponseEntity.badRequest().body("新密码不能为空");
            }
            adminUserService.changePassword(id, request.getNewPassword());
            return ResponseEntity.ok("密码修改成功");
        } catch (Exception e) {
            logger.error("修改密码失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body("密码修改失败: " + e.getMessage());
        }
    }

    @PostMapping("/{id}/verify-password")
    public ResponseEntity<Boolean> verifyPassword(@PathVariable Long id,
                                                  @RequestBody VerifyPasswordRequest request) {
        try {
            boolean isValid = adminUserService.verifyCurrentPassword(id, request.getCurrentPassword());
            return ResponseEntity.ok(isValid);
        } catch (Exception e) {
            logger.error("验证密码失败: {}", e.getMessage());
            return ResponseEntity.ok(false);
        }
    }

    private AdminUser convertToEntity(AdminUserDTO dto) {
        AdminUser adminUser = new AdminUser();
        BeanUtils.copyProperties(dto, adminUser);
        adminUser.setRealName(dto.getRealName());
        return adminUser;
    }

    public static class ChangePasswordRequest {
        private String newPassword;

        public String getNewPassword() {
            return newPassword;
        }

        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }

    public static class VerifyPasswordRequest {
        private String currentPassword;

        public String getCurrentPassword() {
            return currentPassword;
        }

        public void setCurrentPassword(String currentPassword) {
            this.currentPassword = currentPassword;
        }
    }
}